package com.fm.service.file.smo;

import java.io.File;
import java.io.IOException;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;

import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.StreamOpenOfficeDocumentConverter;

//import com.artofsolving.jodconverter.DocumentConverter;
//import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
//import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
//import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;

@Service
public class Office2PdfSMOImpl {

	// OpenOffice的安装目录,默认会安装到c盘下
	private static String OpenOffice_HOME = "C:/Program Files (x86)/OpenOffice 4/program/";
	// 启动服务的命令
	private static String command = "soffice.exe -headless -accept=\"socket,host=127.0.0.1,port=8100;urp;\"";
	//如果启动了一次，不在启动
	private static final boolean hasStart = false;
	
	private static final Logger logger = LogManager.getLogger(Office2PdfSMOImpl.class);

	/**
	 * 核心转pdf方法
	 * 
	 * @param sourcefile
	 *            被转文件
	 * @param targetfile
	 *            目标文件即pdf文件
	 * @return
	 */
	public static void convertTo(File sourcefile, File targetfile) {
		// 目标文件
		Process process = null;
		try {
			// 启动方法
			process = startOpenOffice();
			// 连接openoffice的端口必须和启动服务的端口一致,
			OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
			connection.connect();
			DocumentConverter converter = new StreamOpenOfficeDocumentConverter(connection);
			// 转换,传入源文件和目标文件;
			converter.convert(sourcefile, targetfile);
			connection.disconnect();
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("文件转换报错..."+e.getMessage());
		} finally {
			// 强制终止进程(不终止线程)
			//process.destroy();
		}
	}

	/**
	 * 启动openOffice服务
	 */
	public static Process startOpenOffice() {
		// 启动OpenOffice的服务的完整命令
		String fullCommand = OpenOffice_HOME + command;
		if(hasStart){
			return null;
		}

		try {
			return Runtime.getRuntime().exec(fullCommand);
		} catch (IOException e) {
			logger.error("启动openOffice报错..."+e.getMessage());
		}
		return null;
	}
}
